﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;

public partial class Tailor_Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            loadItem();
            //loadNote();
            loadEmployee();
            initialLoad();
            loadLoginInHiddenField();
        }
    }

    private void loadEmployee()
    {
        string sql = @"
SELECT [EmployeeID] as ID
      ,[EmployeeName] as Name 
from Tailor_Employee where NoteDetails=1 and BranchID=1
";
        DataSet ds = CommonManager.SQLExec(sql);

        ddlMasterName.Items.Clear();

        ddlMasterName.DataSource = ds.Tables[0];
        ddlMasterName.DataTextField = "Name";
        ddlMasterName.DataValueField = "ID";
        ddlMasterName.DataBind();
        //ddlMasterName.Items.Insert(0, new ListItem("Select Extra Design", "0"));
    }

    private void loadNote(int productID)
    {
        string sql = @"
SELECT [NoteID] as ID
      ,[NoteName] as Name 
from Tailor_Note where ProductID="+productID+@"
";
        DataSet ds = CommonManager.SQLExec(sql);

        ddlExtraDesign.Items.Clear();
        
        ddlExtraDesign.DataSource = ds.Tables[0];
        ddlExtraDesign.DataTextField = "Name";
        ddlExtraDesign.DataValueField = "ID";
        ddlExtraDesign.DataBind();
        ddlExtraDesign.Items.Insert(0,new ListItem("Select Extra Design", "0"));
    }

    private void loadLoginInHiddenField()
    {
        if (hfLoginID.Value == "")
        {
            hfLoginID.Value = getLogin().LoginID.ToString();
        }
    }

    private Login getLogin()
    {
        Login login = new Login();

        try
        {
            if (Session["Login"] != null)
            {
                login = (Login)Session["Login"];
            }
            else if (hfLoginID.Value != "")
            {
                login = LoginManager.GetLoginByID(int.Parse(hfLoginID.Value));
            }
            else
            { Session["PreviousPage"] = HttpContext.Current.Request.Url.AbsoluteUri; Response.Redirect("../LoginPage.aspx"); }

        }
        catch (Exception ex)
        { }

        return login;
    }
    private void initialLoad()
    {
        txtOrderDate.Text = DateTime.Today.ToString("dd MMM yyyy");
        txtTrialDate.Text = DateTime.Today.AddDays(7).ToString("dd MMM yyyy");
        txtDelivaryDate.Text = DateTime.Today.AddDays(15).ToString("dd MMM yyyy");
    }

    private void loadItem()
    {
        string sql = @"

SELECT [ProductID] as ID
      ,[ProductName] as Name
FROM [Tailor_Product]
";
        DataSet ds = CommonManager.SQLExec(sql);
        ddlItem.Items.Clear();
        foreach (DataRow dr in ds.Tables[0].Rows)
        {
            ListItem li = new ListItem(dr["Name"].ToString(), dr["ID"].ToString());
            ddlItem.Items.Add(li);
        }
    }
    private void loaddata()
    {
        string sql = @"

SELECT Tailor_DesignProduct.[DesignID] as ID,DesignName as Name
      ,[Group] 
  FROM [Tailor_DesignProduct] inner join Tailor_Design on Tailor_Design.DesignID =Tailor_DesignProduct.DesignID
where Tailor_DesignProduct.ProductID=" + ddlItem.SelectedValue + @" order by Tailor_DesignProduct.Ordering

SELECT Tailor_MasterKolProduct.[MasterKolID] as ID,MasterKolName as Name
  FROM [Tailor_MasterKolProduct] inner join Tailor_MasterKol on Tailor_MasterKol.MasterKolID= Tailor_MasterKolProduct.MasterKolID
where Tailor_MasterKolProduct.ProductID=" + ddlItem.SelectedValue + @"  order by Tailor_MasterKolProduct.Ordering

SELECT Tailor_MeasurementProduct.[MeasurementID] as ID,MeasurementName as Name
  FROM [Tailor_MeasurementProduct] inner join Tailor_Measurement on  Tailor_Measurement.MeasurementID= Tailor_MeasurementProduct.[MeasurementID]
where Tailor_MeasurementProduct.ProductID=" + ddlItem.SelectedValue + @"  order by Tailor_MeasurementProduct.Ordering

SELECT ExtraField1
FROM [Tailor_Product] where  ProductID=" + ddlItem.SelectedValue + @"

SELECT Tailor_Design_MeasurementProduct.[Design_MeasurementID] as ID,Design_MeasurementName as Name
      ,[Group] 
  FROM [Tailor_Design_MeasurementProduct] inner join Tailor_Design_Measurement on Tailor_Design_Measurement.Design_MeasurementID =Tailor_Design_MeasurementProduct.Design_MeasurementID
where Tailor_Design_MeasurementProduct.ProductID=" + ddlItem.SelectedValue + @" order by Tailor_Design_MeasurementProduct.Ordering

";

        DataSet ds = CommonManager.SQLExec(sql);
        
        gvDesign.DataSource = ds.Tables[0];
        gvDesign.DataBind();

        gvMasterKol.DataSource = ds.Tables[1];
        gvMasterKol.DataBind();

        gvMeasurement.DataSource = ds.Tables[2];
        gvMeasurement.DataBind();

        txtItemCharge.Text = ds.Tables[3].Rows[0][0].ToString();
        
        gvDesign_Measurement.DataSource = ds.Tables[4];
        gvDesign_Measurement.DataBind();

        loadNote(int.Parse(ddlItem.SelectedValue));
    }

    protected void ddlItem_SelectedIndexChanged(object sender, EventArgs e)
    {
        loaddata();
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        string otherThanOrderDetails = "";
        string sql = @"Declare @OrderID int
                       Declare @OrderDetailsID int
";
        if (txtOrderNo.Text != "")
        {
            sql += @"
                Set @OrderID=" + txtOrderNo.Text;
        }
        else
        {
            sql += @"INSERT INTO [Tailor_Order]
           ([CustomerID]
           ,[TotalAmount]
           ,[FabricDue]
           ,[DesignCharge]
           ,[OrderDate]
           ,[TrialDate]
           ,[DelivaryDate]
           ,[OtherCharges]
           ,[Discount]
           ,[PaidAmount]
           ,[DueAmount]
           ,[ExtraField10]
           ,[ExtraField1]
           ,[ExtraField2]
           ,[ExtraField3]
           ,[ExtraField4]
           ,[ExtraField5]
           ,[ExtraField6]
           ,[ExtraField7]
           ,[ExtraField8]
           ,[ExtraField9]
           ,[WorkStationID]
           ,[RowStatusID]
           ,[AddedBy]
           ,[AddedDate]
           ,[UpdatedDate]
           ,[UpdatedBy])
     VALUES
           (0--<CustomerID, int,>
           ,0--<TotalAmount, decimal(18,2),>
           ,0--<FabricDue, decimal(18,2),>
           ,0--<DesignCharge, decimal(18,2),>
           ,GETDATE()--<OrderDate, datetime,>
           ,GETDATE()--<TrialDate, datetime,>
           ,GETDATE()--<DelivaryDate, datetime,>
           ,0--<OtherCharges, decimal(18,2),>
           ,0--<Discount, decimal(18,2),>
           ,0--<PaidAmount, decimal(18,2),>
           ,0--<DueAmount, decimal(18,2),>
           ,''--<ExtraField10, nvarchar(max),>
           ,''--<ExtraField1, nvarchar(max),>
           ,''--<ExtraField2, nvarchar(max),>
           ,''--<ExtraField3, nvarchar(max),>
           ,''--<ExtraField4, nvarchar(max),>
           ,''--<ExtraField5, nvarchar(max),>
           ,''--<ExtraField6, nvarchar(max),>
           ,''--<ExtraField7, nvarchar(max),>
           ,''--<ExtraField8, nvarchar(max),>
           ,''--<ExtraField9, nvarchar(max),>
           ," + ConfigurationManager.AppSettings["WorkStationID"].ToString() + @"--<WorkStationID, int,>
           ,0--<RowStatusID, int,>
           ," + getLogin().LoginID + @"--<AddedBy, int,>
           ,GETDATE()--<AddedDate, datetime,>
           ,GETDATE()--<UpdatedDate, datetime,>
           ," + getLogin().LoginID + @"--<UpdatedBy, int,>
           );

SET @OrderID =SCOPE_IDENTITY();
";
        }
        
        string design = "";
            foreach (GridViewRow gvr in gvDesign.Rows)
            {
                CheckBox chkSelect = (CheckBox)gvr.FindControl("chkSelect");
                if (chkSelect.Checked)
                {
                    design+=(design==""?"":", ")+ chkSelect.Text;

                    otherThanOrderDetails += @"
                    INSERT INTO [Tailor_OrderDetailsDesign]
           ([OrderDetailsID]
           ,[DesignID])
     VALUES
           (@OrderDetailsID--<OrderDetailsID, int,>
           ," + chkSelect.ToolTip + @"--<DesignID, int,>
            );
                ";
                    
                }
            }

            

            string MasterKol = "";

            foreach (GridViewRow gvr in gvMasterKol.Rows)
            {
                CheckBox chkSelect = (CheckBox)gvr.FindControl("chkSelect");
                if (chkSelect.Checked)
                {
                    MasterKol += (MasterKol == "" ? "" : ", ") + chkSelect.Text;

                    otherThanOrderDetails += @"
                    INSERT INTO Tailor_OrderDetailsMasterkol
           ([OrderDetailsID]
           ,[MasterkolID])
     VALUES
           (@OrderDetailsID--<OrderDetailsID, int,>
           ," + chkSelect.ToolTip + @"--<MasterkolID, int,>
            );
                ";
                      
                }
            }

            string Measurement = "";

            foreach (GridViewRow gvr in gvMeasurement.Rows)
            {
                TextBox txtAmount = (TextBox)gvr.FindControl("txtAmount");
                Label lblMeasurement = (Label)gvr.FindControl("lblMeasurement");
                if (txtAmount.Text.Trim()!="")
                {

                    Measurement += (Measurement == "" ? "" : ", ") + lblMeasurement.Text + "(" + txtAmount.Text + ")";

                    otherThanOrderDetails += @"
                    INSERT INTO Tailor_OrderDetailsMeasurement
           ([OrderDetailsID]
           ,[MeasurementID],Measurement)
     VALUES
           (@OrderDetailsID--<OrderDetailsID, int,>
               ," + txtAmount.ToolTip + @"--<DesignID, int,>
               ," + txtAmount.Text + @" 
                );
                ";
                      
                }
            }


            string Design_Measurement = "";

            foreach (GridViewRow gvr in gvDesign_Measurement.Rows)
            {
                TextBox txtAmount = (TextBox)gvr.FindControl("txtAmount");
                Label lblMeasurement = (Label)gvr.FindControl("lblMeasurement");
                if (txtAmount.Text.Trim() != "")
                {

                    Design_Measurement += (Design_Measurement == "" ? "" : ", ") + lblMeasurement.Text + "(" + txtAmount.Text + ")";

                    otherThanOrderDetails += @"
                    INSERT INTO Tailor_OrderDetailsDesign_Measurement
           ([OrderDetailsID]
           ,[Design_MeasurementID],Design_Measurement)
     VALUES
           (@OrderDetailsID--<OrderDetailsID, int,>
               ," + txtAmount.ToolTip + @"--<DesignID, int,>
               ," + txtAmount.Text + @" 
                );
                ";

                }
            }

            sql += @"
            INSERT INTO [Tailor_OrderDetails]
           ([OrderID]
           ,[MasterName]
           ,[ProductID]
           ,[Quantity]
           ,[Note]
           ,[Charge]
           ,[Discount]
           ,[TotalPayable]
           ,[ExtraField1]
           ,[ExtraField2]
           ,[ExtraField3]
           ,[ExtraField4]
           ,[ExtraField5]
           ,[RowStatusID]
           ,[AddedBy]
           ,[AddedDate]
           ,[UpdatedDate]
           ,[UpdatedBy])
     VALUES
           (@OrderID--<OrderID, int,>
           ,'" + ddlMasterName.SelectedValue + @"'--<MasterName, nvarchar(256),>
           ," + ddlItem.SelectedValue + @"--<ProductID, int,>
           ," + txtItemQty.Text + @"--<Quantity, int,>
           ,'" + txtNote.Text + @"'--<Note, nvarchar(max),>
           ," + (int.Parse(txtItemCharge.Text)* int.Parse(txtItemQty.Text)).ToString() + @"--<Charge, decimal(18,2),>
           ,0--<Discount, decimal(18,2),>
           ," + (int.Parse(txtItemCharge.Text) * int.Parse(txtItemQty.Text)).ToString() + @"--<TotalPayable, decimal(18,2),>
           ,N'" +Measurement+@"'--<ExtraField1, nvarchar(max),>
           ,N'" + design + @"'--<ExtraField2, nvarchar(max),>
           ,N'" + MasterKol + @"'--<ExtraField3, nvarchar(max),>
           ,N'" + Design_Measurement + @"'--<ExtraField4, nvarchar(max),>
           ,''--<ExtraField5, nvarchar(max),>
           ,0--<RowStatusID, int,>
           ," +getLogin().LoginID+@"--<AddedBy, int,>
           ,GETDATE()--<AddedDate, datetime,>
           ,GETDATE()--<UpdatedDate, datetime,>
           ," + getLogin().LoginID + @"--<UpdatedBy, int,>
           );
SET @OrderDetailsID =SCOPE_IDENTITY()
";

            txtOrderNo.Text = CommonManager.SQLExec(sql + otherThanOrderDetails + "Select @OrderID;").Tables[0].Rows[0][0].ToString();
           loadOrderDetails();
    }
    protected void lbDelete_Click(object sender, EventArgs e)
    {
        LinkButton linkButton = new LinkButton();
        linkButton = (LinkButton)sender;
        CommonManager.SQLExec("Delete Tailor_OrderDetails where OrderDetailsID="+linkButton.CommandArgument);
        loadOrderDetails();
    }

    private void loadOrderDetails()
    {
        string sql = @"
            SELECT Tailor_OrderDetails.[OrderDetailsID]
                  ,Tailor_OrderDetails.[OrderID]
                  ,Tailor_Employee.EmployeeName as MasterName
                  ,Tailor_OrderDetails.[ProductID]
                  ,Tailor_OrderDetails.[Quantity]
                  ,Tailor_OrderDetails.[Note]
                  ,Tailor_OrderDetails.[Charge]
                  ,Tailor_OrderDetails.[Discount]
                  ,Tailor_OrderDetails.[TotalPayable]
                  ,Tailor_OrderDetails.[ExtraField1]
                  ,Tailor_OrderDetails.[ExtraField2]
                  ,Tailor_OrderDetails.[ExtraField3]
                  ,Tailor_OrderDetails.[ExtraField4]
                  ,Tailor_OrderDetails.[ExtraField5]
                  ,Tailor_OrderDetails.[RowStatusID]
                  ,Tailor_OrderDetails.[AddedBy]
                  ,Tailor_OrderDetails.[AddedDate]
                  ,Tailor_OrderDetails.[UpdatedDate]
                  ,Tailor_OrderDetails.[UpdatedBy]
            ,Tailor_Product.ProductName
              FROM [Tailor_OrderDetails]
            inner join Tailor_Product on Tailor_Product.ProductID =Tailor_OrderDetails.[ProductID]
            inner join Tailor_Employee on Tailor_Employee.EmployeeID =Tailor_OrderDetails.[MasterName]
            where Tailor_OrderDetails.[OrderID]=" + txtOrderNo.Text+ @"
            order by Tailor_Product.ProductName,Tailor_OrderDetails.[OrderDetailsID]
            ";

        DataSet ds = CommonManager.SQLExec(sql);
        
        int itemCount = 0;
        decimal totalCharge = 0;
        
        foreach (DataRow dr in ds.Tables[0].Rows)
        {
            itemCount += int.Parse(dr["Quantity"].ToString());
            totalCharge += decimal.Parse(dr["Charge"].ToString());
        }

        gvOrderDetails.DataSource = ds;
        gvOrderDetails.DataBind();

        txtTotalQty.Text = itemCount.ToString();
        txtTotalCharge.Text = totalCharge.ToString("0");
        recalculate();
        ((Label)gvOrderDetails.FooterRow.FindControl("lblTotalCharge")).Text = totalCharge.ToString("0");
        ((Label)gvOrderDetails.FooterRow.FindControl("lblTotalQty")).Text = itemCount.ToString();
    }
    protected void txtCustomerPhone_TextChanged(object sender, EventArgs e)
    {
        DataSet ds = CommonManager.SQLExec("select CustomerName,Mobile,Pos_CustomerID from Pos_Customer where Mobile like '%" + txtCustomerPhone.Text + "%'");

        if (ds.Tables[0].Rows.Count > 0)
        {
            txtCustomerName.Text = ds.Tables[0].Rows[0]["CustomerName"].ToString();
            txtCustomerID.Text = ds.Tables[0].Rows[0]["Pos_CustomerID"].ToString();
        }
    }
    protected void txtFabricDue_TextChanged(object sender, EventArgs e)
    {
        recalculate();
    }

    private void recalculate()
    {
        txtTotalPayable.Text = (decimal.Parse(txtTotalCharge.Text) + decimal.Parse(txtDesignCharge.Text) + decimal.Parse(txtFabricDue.Text) - decimal.Parse(txtDiscount.Text)).ToString("0");

        txtDUE.Text = (decimal.Parse(txtTotalPayable.Text) - decimal.Parse(txtPaymentCash.Text) - decimal.Parse(txtPaymentCardDBBL.Text) - decimal.Parse(txtPaymentCardCITY.Text)).ToString("0");
    }
    protected void txtDesignCharge_TextChanged(object sender, EventArgs e)
    {
        recalculate();
    }
    protected void txtDiscount_TextChanged(object sender, EventArgs e)
    {
        recalculate();
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (txtCustomerPhone.Text == "")
        {
            CommonManager.showAlartMessage("Please provice the customer phone no.", this.Page);
            return;
        }
        string sql = @"Declare @CustomerID int
                        ";

        if (txtCustomerID.Text != "")
        {
            sql += "set @CustomerID=" + txtCustomerID.Text;
        }
        else
        {
            sql += @"
           INSERT INTO [Pos_Customer]
           ([CardNo]
           ,[Signature]
           ,[CustomerName]
           ,[ReferenceID]
           ,[Address]
           ,[Mobile]
           ,[Phone]
           ,[DiscountPersent]
           ,[Note]
           ,[ExtraFiled1]
           ,[ExtraFiled2]
           ,[ExtraFiled3]
           ,[ExtraFiled4]
           ,[ExtraFiled5]
           ,[AddedBy]
           ,[AddedDate]
           ,[UpdatedBy]
           ,[UpdatedDate]
           ,[RowSatatusID]
           ,[DateofBirth]
           ,[ApplicationDate]
           ,[CardIssueDate]
           ,[ExpireDate]
           ,[CardType]
           ,[ApprovedBy])
     VALUES
           (''--<CardNo, varchar(12),>
           ,''--<Signature, nvarchar(256),>
           ,'"+txtCustomerName.Text+@"'--<CustomerName, varchar(50),>
           ,0--<ReferenceID, int,>
           ,''--<Address, varchar(50),>
           ,'" + txtCustomerPhone.Text + @"'--<Mobile, varchar(20),>
           ,''--<Phone, varchar(256),>
           ,0--<DiscountPersent, decimal(5,2),>
           ,''--<Note, varchar(50),>
           ,''--<ExtraFiled1, nvarchar(256),>
           ,''--<ExtraFiled2, nvarchar(256),>
           ,''--<ExtraFiled3, nvarchar(256),>
           ,''--<ExtraFiled4, nvarchar(256),>
           ,''--<ExtraFiled5, nvarchar(256),>
           ,"+getLogin().LoginID+@"--<AddedBy, int,>
           ,GETDATE()--<AddedDate, datetime,>
           ," + getLogin().LoginID + @"--<UpdatedBy, int,>
           ,GETDATE()--<UpdatedDate, datetime,>
           ,1--<RowSatatusID, int,>
           ,GETDATE()--<DateofBirth, datetime,>
           ,GETDATE()--<ApplicationDate, datetime,>
           ,GETDATE()--<CardIssueDate, datetime,>
           ,GETDATE()--<ExpireDate, datetime,>
           ,''--<CardType, nvarchar(50),>
           ,''--<ApprovedBy, nvarchar(256),>
           );
SET @CustomerID =SCOPE_IDENTITY();
";
        }
        if (txtOrderNo.Text == "")
        {
            CommonManager.showAlartMessage("Please add aleast 1 order.", this.Page);
            return;
        }
        sql += @"
UPDATE [Tailor_Order]
   SET [CustomerID] = @CustomerID--<CustomerID, int,>
      ,[TotalAmount] = "+txtTotalCharge.Text+@"--<TotalAmount, decimal(18,2),>
      ,[FabricDue] = " + txtFabricDue.Text + @"--<FabricDue, decimal(18,2),>
      ,[DesignCharge] = " + txtDesignCharge.Text + @"--<DesignCharge, decimal(18,2),>
      ,[OrderDate] = '" + DateTime.Parse(txtOrderDate.Text).ToString("yyyy-MM-dd") + @"'--<OrderDate, datetime,>
      ,[TrialDate] = '" + DateTime.Parse(txtTrialDate.Text).ToString("yyyy-MM-dd") + @"'--<TrialDate, datetime,>
      ,[DelivaryDate] = '" + DateTime.Parse(txtDelivaryDate.Text).ToString("yyyy-MM-dd") + @"'--<DelivaryDate, datetime,>
      ,[OtherCharges] = " + txtTotalPayable.Text + @"--<OtherCharges, decimal(18,2),>
      ,[Discount] = " + txtDiscount.Text + @"--<Discount, decimal(18,2),>
      ,[PaidAmount] = " + (decimal.Parse(txtPaymentCash.Text) + decimal.Parse(txtPaymentCardDBBL.Text) + decimal.Parse(txtPaymentCardCITY.Text)).ToString("0.00") + @"--<PaidAmount, decimal(18,2),>
      ,[DueAmount] = " + txtDUE.Text + @"--<DueAmount, decimal(18,2),>
      --,[ExtraField10] = [ExtraField10]--<ExtraField10, nvarchar(max),>
      ,[ExtraField1] = '" + txtPaymentCash.Text + @"'--<ExtraField1, nvarchar(max),>
      ,[ExtraField2] = '" + txtPaymentCardDBBL.Text + @"'--<ExtraField2, nvarchar(max),>
      ,[ExtraField3] = '" + txtPaymentCardCITY.Text + @"'--<ExtraField3, nvarchar(max),>
      --,[ExtraField4] = [ExtraField4]--<ExtraField4, nvarchar(max),>
      --,[ExtraField5] = --<ExtraField5, nvarchar(max),>
      --,[ExtraField6] = --<ExtraField6, nvarchar(max),>
      --,[ExtraField7] = --<ExtraField7, nvarchar(max),>
      --,[ExtraField8] = --<ExtraField8, nvarchar(max),>
      --,[ExtraField9] = --<ExtraField9, nvarchar(max),>
      --,[WorkStationID] = --<WorkStationID, int,>
      ,[RowStatusID] = 1--<RowStatusID, int,>
      --,[AddedBy] = --<AddedBy, int,>
      --,[AddedDate] = --<AddedDate, datetime,>
      --,[UpdatedDate] = --<UpdatedDate, datetime,>
      --,[UpdatedBy] = --<UpdatedBy, int,>
 WHERE OrderID="+txtOrderNo.Text+@";
";

        CommonManager.SQLExec(sql);

        Response.Redirect("CustomerSlip.aspx?orderID="+txtOrderNo.Text);
    }
    protected void ddlExtraDesign_SelectedIndexChanged(object sender, EventArgs e)
    {

        string sql = @"
SELECT [NoteID] as ID
      ,[NoteName] as Name 
,ProductID,NoteDetails
  FROM Tailor_Note  where [NoteID]=" + ddlExtraDesign.SelectedValue;
        DataSet ds = CommonManager.SQLExec(sql);

        if (ds.Tables[0].Rows.Count > 0)
        {
            txtNote.Text = ds.Tables[0].Rows[0][3].ToString();
        }
        else
        {
            txtNote.Text = "";
        }
    }
}